package tech.wetech.admin.service.system.impl;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tech.wetech.admin.service.system.FileStorageService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private ServletContext servletContext;
    @Override
    public void deleteFile(String filePath) {
        Path webAppRoot = Paths.get(servletContext.getRealPath("/"));
        System.out.println("Resolved path: " + webAppRoot.toAbsolutePath());
        Path pfilePath = webAppRoot.resolve(filePath);
        System.out.println("Resolved path: " + pfilePath.toAbsolutePath());
        try {
            if (Files.exists(pfilePath)) {
                Files.delete(pfilePath);
            }
            if (Files.exists(pfilePath)) {
                Files.deleteIfExists(pfilePath);
            }
        }catch (AccessDeniedException e) {
            System.err.println("Access denied: " + e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException("Failed to delete file", e);
        }
    }
}
